package com.loiane.util;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class GenericUtil<E,K> {
	@Autowired(required=false)	
	private Class tipo;
	@Autowired(required=false)	
	private Class llave;
	
	public List<E> getContactsFromRequest(Object data){
		List<E> list;
		if (data.toString().indexOf('[') > -1){
			list = getListContactsFromJSON(data);
		} else { 
			E contact = getContactFromJSON(data);
			list = new ArrayList<E>();
			list.add(contact);
		}
		return list;
	}


	@SuppressWarnings("unchecked")
	private E getContactFromJSON(Object data){
		JSONObject jsonObject = JSONObject.fromObject(data);
		E newContact = ((E) JSONObject.toBean(jsonObject, tipo));
		return newContact;
	}

	@SuppressWarnings("unchecked")
	private List<E> getListContactsFromJSON(Object data){
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<E> newContacts = (List<E>) JSONArray.toCollection(jsonArray, tipo);
		return newContacts;
	}

	public List<K> getKeysFromRequest(Object data){
		List<K> list;
		if (data.toString().indexOf('[') > -1){
			list = getListIdFromJSON(data);
		} else { 
			K contact = getKeyFromJSON(data);
			list = new ArrayList<K>();
			list.add(contact);
		}
		return list;
	}
	
	@SuppressWarnings("unchecked")
	private List<K> getListIdFromJSON(Object data){
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<K> idContacts = (List<K>) JSONArray.toCollection(jsonArray,llave);
		return idContacts;
	}
	
	@SuppressWarnings("unchecked")
	private K getKeyFromJSON(Object data){
		JSONObject jsonObject = JSONObject.fromObject(data);
		K newKey = ((K) JSONObject.toBean(jsonObject, llave));
		return newKey;
	}

	public void setTipo(Class tipo) {
		this.tipo = tipo;
	}

	public void setLlave(Class llave) {
		this.llave = llave;
	}
}

